// TestClient.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <time.h>

VOID ProcessPacket( net::INetPacket* pPacket );
typedef std::list< net::network_t > HandleList;
HandleList handleList;
extern net::PacketProtocal ProtocalCustom;

int _tmain(int argc, _TCHAR* argv[])
{
	net::CreateNetwork( net::asio );
	net::InitNetwork( 10 );

	net::IMessageQueue* mQueue = xgc_nullptr;
	//for( int i = 0; i < 1000; ++i )
	{
		net::AsyncConnectServer( "127.0.0.1", 30120, ProtocalCustom, &mQueue, 1000, 15000 );
	}

	clock_t last = clock();
	while( mQueue )
	{
		net::INetPacket* pPacket = mQueue->PopMessage();
		if( pPacket )
		{
			ProcessPacket( pPacket );
			pPacket->release();
		}
		else
		{
			Sleep(1);
		}
	}

	mQueue->Release();

	net::FiniNetwork();
	net::DestroyNetwork();
	return 0;
}

void ProcessAccept( net::network_t h )
{
	net::Param_SetUserdata _set;
	_set.handle = h;
	_set.userdata_ptr = xgc_nullptr;
	net::ExecuteState( Operator_SetUserdata, (xgc_long_ptr) &_set );

	handleList.push_back( h );

	printf( "accept link %d \n", h );
}

void ProcessClose( net::network_t h, xgc_lpvoid userdata )
{
	HandleList::iterator i = std::find( handleList.begin(), handleList.end(), h );
	if( i != handleList.end() )
		handleList.erase( i );

	SAFE_DELETE( userdata );
	printf( "close link %d \n", h );
}

void ProcessError( net::network_t h, int e )
{
	net::CloseLink( h );
}

VOID ProcessPacket( net::INetPacket* pPacket )
{
	bufstream buf( pPacket->header(), pPacket->size() );
	xgc_uint16 length;
	xgc_byte type, code;
	buf >> length >> type >> code;
	switch( type )
	{
	case SYSTEM_MESSAGE_TYPE:
		switch( code )
		{
		case EVENT_CONNECT:
			ProcessAccept( pPacket->handle() );
			break;
		case EVENT_CLOSE:
			ProcessClose( pPacket->handle(), pPacket->userdata() );
			break;
		case EVENT_ERROR:
			ProcessError( pPacket->handle(), *(int*)buf.rd_ptr() );
			break;
		}
		break;
	default:
		{
			net::SendPacket( pPacket->handle(), pPacket->header(), pPacket->size() );
		}
	}
}